const { Journal, User, Order, Car, UserRegion } = require('../models');
const { Op } = require('sequelize');
const dayjs = require('dayjs');

class JournalService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter, page = 1, page_size = 20) {
		const { user_id } = filter;
		const where = {};
		if (user_id) where['user_id'] = user_id;

		const { count: total, rows: data } = await Journal.findAndCountAll({
			where,
			include: [{
				model: User,
				as: 'user'
			}, {
				model: Order,
				as: 'order'
			}],

			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['id', 'asc']
			]
		});

		return {
			data,
			total
		}
	}

	async info(where) {
		return await Journal.findOne({
			where
		});
	}

	async dispatch(out_trade_no) {
		const data = await Order.findOne({
			where: {
				out_trade_no
			},
			include: [
				'buyer',
				{
					model: Car,
					as: 'car',
					include: ['category']
				}]
		});
		const { id, pay_status, status, buyer: { tree_id }, car, draft_user_id, reg_city, quantity = 1 } = data;
		if (!id) return false;

		const { award = 0, commission = 0, bonus = 0 } = car;

		//推荐奖励
		if (tree_id) {
			const amount = quantity * award * 1;

			//判断是否派发过推荐奖
			let { id: journalId } = await Journal.findOne({
				where: {
					order_id: id,
					type: 1,
					user_id: tree_id
				}
			}) || {};
			if (!journalId) {
				journalId = await Journal.create({
					order_id: id,
					type: 1,
					user_id: tree_id,
					amount
				}).then(({ id }) => id);
			}

			if (status === 3) {
				await Journal.update({
					status: 1
				}, {
					where: {
						id: journalId
					}
				});

				await Order.update({
					award: amount
				}, {
					where: {
						id
					}
				});

				if (parseInt(data.award) === 0 && amount > 0) {
					const user = await User.findByPk(tree_id);
					if (user) await user.increment(['balance'], { by: amount });
				}
			}
		}

		//佣金奖励
		if (draft_user_id) {
			const amount = quantity * commission * 1;

			let { id: journalId } = await Journal.findOne({
				where: {
					order_id: id,
					type: 2,
					user_id: draft_user_id
				}
			}) || {};
			if (!journalId) {
				journalId = await Journal.create({
					order_id: id,
					type: 2,
					user_id: draft_user_id,
					amount
				}).then(({ id }) => id);
			}

			//已完结
			if (status === 3) {
				await Journal.update({
					status: 1
				}, {
					where: {
						id: journalId
					}
				});

				await Order.update({
					commission: amount
				}, {
					where: {
						id
					}
				});

				if (parseInt(data.commission) === 0 && amount > 0) {
					const user = await User.findByPk(draft_user_id);
					if (user) await user.increment(['balance'], { by: amount });
				}
			}
		}

		//分红奖励
		//判断上牌城市及车辆分类下是否有平台合伙人
		const { user_id: coop_id } = await UserRegion.findOne({
			include: {
				model: User,
				as: 'user',
				attributes: ['role_id']
			},
			where: {
				_city_id: reg_city[1],
				category_id: car.category_id,
				user_id: { [Op.gt]: 0 },
				'$user.role_id$': 3
			}
		}) || {};

		//平台合伙人不能给自己分红
		if (coop_id && draft_user_id !== coop_id) {
			//判断用户是否存在
			/*
			const { id } = await User.findOne({ where: { id: coop_id, role_id: 3 } }) || {};
			if (!id) return true;
			*/

			const amount = quantity * bonus * 1;
			let { id: journalId } = await Journal.findOne({
				where: {
					order_id: id,
					type: 3,
					user_id: coop_id
				}
			}) || {};
			if (!journalId) {
				journalId = await Journal.create({
					order_id: id,
					type: 3,
					user_id: coop_id,
					amount
				}).then(({ id }) => id);
			}

			//已完结
			if (status === 3) {
				await Journal.update({
					status: 1
				}, {
					where: {
						id: journalId
					}
				});

				await Order.update({
					bonus: amount
				}, {
					where: {
						id
					}
				});

				if (parseInt(data.bonus) === 0 && amount > 0) {
					const user = await User.findByPk(coop_id);
					if (user) await user.increment(['balance'], { by: amount });
				}
			}
		}

		return true;
	}
}

exports = module.exports = JournalService;
